import Vue from 'vue'
import VueRouter from 'vue-router'
import Login from '../components/Login.vue'
import Home from '../components/Home.vue'
import Welcome from '../components/Welcome.vue'
import User from '../components/user/User.vue'

Vue.use(VueRouter)

const routes = [{
    path: '/',
    redirect: '/login'
  },
  {
    path: '/login',
    component: Login
  },
  {
    path: '/home',
    component: Home,
    redirect: '/welcome',
    children: [{
        path: '/welcome',
        component: Welcome,
        redirect: '/user',
      },
      {
        path: '/user',
        component: User
      }
    ]
  }
]

const router = new VueRouter({
  routes
})
// 挂载路由导航守卫
// to为将要访问的路径
//from代表从哪个路径跳转而来
//next是一个函数，表示放行
//next()放行  next('/login')强制跳转
router.beforeEach((to, from, next) => {
  if (to.path === '/login') return next()
  //如果要去登录页，则直接放行，这也是默认的操作
  const tokenStr = window.sessionStorage.getItem('token')
  //判断token是否为空，如果为空，强制跳转到login页，否则放行
  if (!tokenStr) return next('/login')
  next()
})
export default router